const modal = require('./modal')
const util = require('./util')
const schema = modal.schema

/**
 * 申请提现
 */
Parse.Cloud.define('cashingApply', async (request, response) => {
  const { id, money } = request.params
  if (!id) {
    return response.error('请提供需要提现的会员Id')
  }
  if (typeof money !== 'number') {
    return response.error('金额非法')
  }
  if (money <= 0) {
    return response.error('请输入大于零的数字')
  }
  try {
    const currentMember = schema.member()
    currentMember.id = id
    const accountQuery = schema.account().query()
    accountQuery.include('member.tbk')
    accountQuery.equalTo('member', currentMember)
    const account = await accountQuery.first()
    const selfIncomes = account.get('selfIncomes') || 0
    const subIncomes = account.get('subIncomes') || 0
    const cashing = account.get('cashing') || 0
    const cashed = account.get('cashed') || 0
    const remaining = selfIncomes + subIncomes - cashing - cashed
    if (money > remaining) {
      return response.error('余额不足')
    } else {
      account.set('cashing', parseFloat((cashing + money).toFixed(4)))
    }
    await account.save()
    const cash = schema.cash()
    await cash.save({
      member: currentMember,
      tbk: account.get('member').get('tbk'),
      sheet: util.generateSheet(),
      money,
      status: 0
    })
    response.success({
      code: 1
    })
  } catch (err) {
    response.error(err.message)
  }
})
/**
 * 根据member获取提现列表
 */
Parse.Cloud.define('getCashApplyByMember', async (request, response) => {
  const { currentPage, pageSize, condition } = request.params
  if (!condition || !condition.id) {
    return response.error('请提供需要提现的会员Id')
  }
  const member = schema.member()
  member.id = condition.id
  const cashQuery = schema.cash().query()
  cashQuery.equalTo('member', member)
  cashQuery.include('approveBy')
  cashQuery.limit(pageSize)
  cashQuery.skip((currentPage - 1) * pageSize)
  cashQuery.descending('updatedAt')  // 以更新时间排序

  const cashCount = cashQuery.count()
  const cashFind = cashQuery.find()
  const cashList = await cashFind
  const count = await cashCount
  const cashResult = cashList.map((item) => {
    const temp = util.mapAttributes(item, ['createdAt', 'sheet', 'money', 'status', 'approveBy'])
    temp.id = item.id
    return temp
  })
  response.success({
    total: count,   // 总数量
    totalPage: Math.ceil(count / pageSize),  // 总页数
    currentPage,   // 当前页
    pageSize,   // 每页数量
    data: cashResult
  })
})
/**
 * 获取提现申请列表
 */
Parse.Cloud.define('getCashApplies', async (request, response) => {
  const { currentPage, pageSize, condition } = request.params
  const cashQuery = schema.cash().query()
  cashQuery.limit(pageSize)
  cashQuery.skip((currentPage - 1) * pageSize)
  cashQuery.include('tbk')
  cashQuery.include('approveBy')
  cashQuery.descending('updatedAt')  // 以更新时间排序
  if (condition) {
    const { tbkId, status } = condition
    if (tbkId) {
      const tbk = schema.tbk()
      tbk.id = tbkId
      cashQuery.equalTo('tbk', tbk)
    }
    if (status) {
      cashQuery.equalTo('status', status)
    }
  }
  const cashCount = cashQuery.count()
  const cashFind = cashQuery.find()
  const cashList = await cashFind
  const count = await cashCount
  const cashResult = cashList.map((item) => {
    const temp = util.mapAttributes(item, ['createdAt', 'sheet', 'money', 'status', 'approveBy'])
    const tbk = item.get('tbk')
    if (tbk) {
      temp.tbkUsername = tbk.get('username')
      temp.tbkId = tbk.id
    }
    temp.id = item.id
    return temp
  })
  response.success({
    total: count,   // 总数量
    totalPage: Math.ceil(count / pageSize),  // 总页数
    currentPage,   // 当前页
    pageSize,   // 每页数量
    data: cashResult
  })
})
/**
 * 提现申请审核
 */
Parse.Cloud.define('checkCashApply', async (request, response) => {
  const { id, status, user } = request.params
  if (!id) {
    return response.error('请提交需要审核的提现申请Id')
  }
  if (status !== 1 && status !== -1) {
    return response.error('状态非法')
  }
  if (!user) {
    return response.error('请提供审核人')
  }
  try {
    const cash = schema.cash()
    const cashQuery = cash.query()
    const account = schema.account()
    const accountQuery = account.query()

    cashQuery.equalTo('objectId', id)
    cashQuery.include('member')
    cashQuery.equalTo('status', 0) // 只查询未审核

    const cashApply = await cashQuery.first()

    if (!cashApply) {
      return response.error('找不到该提现申请')
    }
    const member = cashApply.get('member')
    accountQuery.equalTo('member', member)
    const currentAccount = await accountQuery.first()
    if (!currentAccount) {
      return response.error('找不到账号')
    }
    const money = cashApply.get('money')
    const cashing = currentAccount.get('cashing') || 0  // 正在提现的金额
    const cashed = currentAccount.get('cashed') || 0 // 已提现的金额
    if (status === 1) {  // 审核通完，正在提现的金额减少，已提现的金额增加
      currentAccount.set('cashing', parseFloat((cashing - money).toFixed(4)))
      currentAccount.set('cashed', parseFloat((cashed + money).toFixed(4)))
    } else { // 审核不通过，释放正在提现的金额
      currentAccount.set('cashing', parseFloat((cashing - money).toFixed(4)))
    }
    const currentUser = new Parse.User()
    currentUser.id = user
    cashApply.set('status', status)
    cashApply.set('approveBy', currentUser)
    const saveCashApply = cashApply.save()
    const saveAccount = currentAccount.save()
    await saveCashApply
    await saveAccount
    response.success({
      code: 1
    })
  } catch (err) {
    response.error(err.message)
  }
})
